let hostname = window.location.hostname;
let port = window.location.port;
const BASE_PATH = "http://"+ hostname + ":" + port;
const VIEW_PATH_PREFIX = BASE_PATH + "/views";   // 视图路径前缀
//loading画面计数值
var loadingsCount = 0;
var loading;

// 默认页面显示条数
const DEFAULT_PAGE_SIZE = 10;

function elMessage(type, msg, callback) {
    let duration = 3000;
    if (callback) {
        duration = 0;
    }
    vm.$message({
        type: type,
        center: true,
        message: msg,
        showClose: true,
        customClass: "el-message-class",
        duration: duration,
        onClose: function () {
            if (callback) {
                callback();
            }
        }
    });
}
function infoMessage(msg, callback) {
    elMessage("info", msg, callback);
}

function warningMessage(msg, callback) {
    elMessage("warning", msg, callback);
}

function successMessage(msg, callback) {
    elMessage("success", msg, callback);
}

function errorMessage(msg, callback) {
    elMessage("error", msg, callback);
}

function showLoading(msg) {
    if (loadingsCount++ > 0) {
        return;
    }
    msg = msg ? msg : "正在加载中......";
    loading = Vue.prototype.$loading({
        lock: true,
        text: msg,
        background: 'rgba(255, 255, 255, 0.7)'
    });
}

function hideLoading() {
    if (loadingsCount-- > 1) {
        return;
    }
    if (loading) {
        loading.close();
        loadingsCount = 0;
    }
}

function myAlert(msg, callback) {
    vm.$alert(msg, {
        customClass: "el-alert-class",
        closeOnPressEscape: true,
        callback: function () {
            if (callback) {
                callback();
            }
        }
    });
}

/**
 *
 * @param msg   提示文字
 * @param confirmCallback   确定回调
 * @param cancelCallback    取消回调
 */
function myConfirm(msg, confirmCallback, cancelCallback) {
    vm.$confirm(msg, {
        title: "提示",
        // customClass: "el-confirm-class",
        cancelButtonClass: 'btn-custom-cancel',
        type: "warning",
        callback: function (action) {
            if (action === "confirm") {
                if (confirmCallback) {
                    confirmCallback();
                }
            } else {
                if (cancelCallback) {
                    cancelCallback();
                }
            }
        }
    });
}

/**
 * 提供一个公用的ajax请求方法，可以统一处理登陆超时，系统出错的返回
 * @param settings 选项
 * <br>
 * url:             访问地址 [String] <br>
 * data:            请求数据 [Object, String]<br>
 * isJson:          是否作为json数据发送 [Boolean]<br>
 * callback:        请求成功，返回200的回调 [Function]<br>
 * errorCallback:   请求出错，返回非401的回调 [Function]<br>
 * errorMsg:        错误提示信息 [String]
 */
function myAjax(settings) {
    let data = settings.data;
    let contentType = "application/x-www-form-urlencoded";
    if (settings.isJson) {
        contentType = "application/json;charset=UTF-8";
        data = JSON.stringify(data);
    }
    $.ajax({
        type: settings.type ? settings.type : "POST",
        contentType: contentType,
        url: settings.url,
        data: data,
        success: function (obj) {
            if (settings.callback) {
                settings.callback(obj);
            }
        },
        error: function(data){
            hideLoading();

            if (settings.errorCallback) {
                settings.errorCallback(data);
                return;
            }
            if (data.status === 401) {
                myAlert("您的登录已超时，请重新登录！", function () {
                    window.top.location.href = BASE_PATH + "/login.html";
                });
                return;
            }

            if(data.responseJSON.message) {
                myAlert(data.responseJSON.message);
                return;
            }

            let msg = "操作失败：";
            if (settings.errorMsg) {
                msg = settings.errorMsg + "：";
            }
            let message = data.message ? data.message : "请联系管理员！";
            myAlert(msg + message);
        }
    });
}

/**
 *  比较：从小到大
 * @param prop  比较的字段
 * @returns {Function}
 * @constructor
 */
let COMPARE_ASC = function (prop) {
    return function (obj1, obj2) {
        let val1 = obj1[prop];
        let val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    }
};
/**
 *  比较：从大到小
 * @param prop  比较的字段
 * @returns {Function}
 * @constructor
 */
let COMPARE_DESC = function (prop) {
    return function (obj1, obj2) {
        let val1 = obj1[prop];
        let val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 > val2) {
            return -1;
        } else if (val1 < val2) {
            return 1;
        } else {
            return 0;
        }
    }
};


// 保存已经存进树结构的节点，有在这不再遍历
let existTreeArr = [];
/**
 *  转树结构，id, parentId：必有字段
 * @param list  要转换的数组
 * @returns {Array} 树结构数组
 */
function toTree(list) {
    existTreeArr = []; //清空之前的

    let tree = [];
    if(list === undefined || list.length < 1){
        return tree;
    }

    // 先按parentId 从小到大排序
    let newList = list.sort(COMPARE_ASC("parentId"));

    for (let i = 0; i < newList.length; i++) {
        let obj = newList[i];

        // 保存过的不再添加
        if (existTreeArr.indexOf(obj.id) === -1) {
            tree.push(findChildren(obj, newList));
        }
    }
    return tree;
}
/**
 * 递归查找子节点
 */
function findChildren(parent, list) {
    for (let i = 0; i < list.length; i++) {
        let children = list[i];
        if(parent.id === children.parentId && existTreeArr.indexOf(children.id) === -1) {
            if (parent.children === undefined) {
                parent.children = [];
            }
            existTreeArr.push(children.id);
            parent.children.push(findChildren(children, list));

        }
    }
    return parent;
}


/**
 * 日期格式化
 * @param fmt
 * @returns {*}
 * @constructor
 */
Date.prototype.Format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/**
 * 是否为空
 * @param val
 * @returns 空 = 返回true
 */
function isEmpty(val) {
    return (val === undefined || val === null || val === "");
}
/**
 * 设置cookie
 * @param key   键
 * @param value 值
 * @param time  时间(秒)
 */
function setCookie(key, value, time){
    if(time) {
        let exp = new Date();
        exp.setTime(exp.getTime() + time * 1000);
        document.cookie= key + "=" + value +";expires=" + exp.toGMTString();
    } else {
        document.cookie= key + "=" + value +";";
    }

}
/**
 * 获取cookie
 * @param key   键
 */
function getCookie(key) {
    let arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}
/**
 * 删除cookie
 * @param key   键
 */
function delCookie(key) {
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    let val = getCookie(key);
    if (val != null) document.cookie = key + "=" + val + ";expires=" + exp.toGMTString();
}

/**
 * 保存信息 7 天
 * @param obj 用户对象
 */
function setCookieUserInfo(obj) {
    let time = 7 * 24 * 60 * 60;
    setCookie("username", obj.username, time);
    setCookie("password", obj.password, time);
    setCookie("rememberMe", obj.rememberMe, time);
}
function delCookieUserInfo() {
    delCookie("username");
    delCookie("password");
    delCookie("rememberMe");
}